package containers;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JPanel;

import runnables.Animated;
import runnables.AnimationLoop;
import sprites.SpriteModels;
import sprites.TestSprite;

public class Testpanel extends JPanel implements Animated{
	private static final long serialVersionUID = 1L;
	
	private SpriteModels sprite;
	private int frame = 0;
	private int animationLength;
	
	private AnimationLoop<Testpanel> cycle;
	
	private boolean animationRunning = false;
	
	public Testpanel(SpriteModels model, boolean opaque, int timer){
		if(model == null){
			throw new IllegalArgumentException("No SpriteModel provided!");
		}
		if(timer < 50){
			timer = 50;
		}
		sprite = model;
		Dimension spriteSize = SpriteModels.getSize(model);
		if(spriteSize == null){
			throw new IllegalArgumentException("SpriteModel not found!");
		}
		setPreferredSize(spriteSize);
		animationLength = SpriteModels.getAnimationLength(sprite);
		if(animationLength < 1){
			throw new IllegalArgumentException("Invalid animation length!");
		}
		
		cycle = new AnimationLoop<Testpanel>(this, timer);
		
		setBackground(Color.WHITE);		
		setOpaque(opaque);
	}
	
	public void advanceFrame(){
		frame = (frame+1)%animationLength;
	}
	
	protected void paintComponent(Graphics g){
		super.paintComponents(g);
		g.drawImage(TestSprite.getFrame(sprite, frame), 0, 0, Color.white, null);
	}
	
	public void repaintBody(){
		repaint();
	}
	
	public void startAnimation(){
		if(animationRunning){
			return;
		}
		animationRunning = true;
		cycle.run();
	}
	
	public void stopAnimation(){
		if (!animationRunning) {
			return;
		}
		animationRunning = false;
		cycle.stopThread();
	}

}
